//
//  MaskLabel.m
//  RDWave
//
//  Created by Mr.Dynasty on 2019/3/12.
//  Copyright © 2019 Mr.Dynasty. All rights reserved.
//

#import "MaskLabel.h"

@implementation MaskLabel

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self customInit];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self customInit];
    }
    return self;
}

- (void)customInit{
    _maskBackgroundColor = [super backgroundColor];
    [super setBackgroundColor:[UIColor clearColor]];
    self.opaque = NO;
    self.maskTextEnabled = YES;
}

- (UIColor *)backgroundColor {
    return _maskBackgroundColor;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    _maskBackgroundColor = backgroundColor;
    [self setNeedsDisplay];
}

- (void)setTextColor:(UIColor *)textColor {
    [super setTextColor:textColor];
    self.maskTextEnabled = NO;
}

- (void)setMaskTextEnabled:(BOOL)maskTextEnabled {
    _maskTextEnabled = maskTextEnabled;
    if (_maskTextEnabled) {
        [super setTextColor:[UIColor whiteColor]];
    }
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    if (!self.maskTextEnabled) {
        [super drawRect:rect];
        return;
    }
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    [super drawRect:rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGImageRef image = CGBitmapContextCreateImage(context);
    UIGraphicsEndImageContext();
    
    context = UIGraphicsGetCurrentContext();
    CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, CGRectGetHeight(rect)));
    
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image), CGImageGetBytesPerRow(image), CGImageGetDataProvider(image), CGImageGetDecode(image), CGImageGetShouldInterpolate(image));
    CFRelease(image);
    image = nil;
    
    CGContextClearRect(context, rect);
    CGContextSaveGState(context);
    CGContextClipToMask(context, rect, mask);
    
    if (self.layer.cornerRadius != 0.0) {
        CGPathRef path = CGPathCreateWithRoundedRect(rect, self.layer.cornerRadius, self.layer.cornerRadius, nil);
        CGContextAddPath(context, path);
        CGContextClip(context);
        CGPathRelease(path);
    }
    
    CFRelease(mask);
    mask = nil;
    
    [self drawRectBackground:rect];
    CGContextRestoreGState(context);
}

- (void)drawRectBackground:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [_maskBackgroundColor set];
    CGContextFillRect(context, rect);
}



@end
